package com.sf.fy.uav.applet.utils;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

/**
 * @author 01430312
 */
public class ImageCompressor {

    public static void compressImage(String inputImagePath, String outputImagePath, float compressionQuality) {
        try {
            // 读取图片文件
            BufferedImage image = ImageIO.read(new File(inputImagePath));

            // 获取图片编码
            Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
            ImageWriter writer = writers.next();

            // 设置压缩参数
            javax.imageio.plugins.jpeg.JPEGImageWriteParam jpegParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);
            jpegParams.setCompressionMode(javax.imageio.plugins.jpeg.JPEGImageWriteParam.MODE_EXPLICIT);
            jpegParams.setCompressionQuality(compressionQuality); // 设置压缩质量

            // 获取输出流
            File outputFile = new File(outputImagePath);
            ImageOutputStream ios = ImageIO.createImageOutputStream(outputFile);

            // 执行压缩
            writer.setOutput(ios);
            writer.write(null, new IIOImage(image, null, null), jpegParams);

            ios.close();
            writer.dispose();

            System.out.println("图片压缩成功！");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("图片压缩失败：" + e.getMessage());
        }
    }

    public static void main(String[] args) {
        // 原始图片路径、压缩后的图片路径和压缩比例因子
        String inputImagePath = "E://1697611534448-null.jpg";
        String outputImagePath = "E://1697611534448-null-new11.jpg";
        float compressionQuality = 0.7f; // 压缩比例，范围0.0到1.0

        compressImage(inputImagePath, outputImagePath, compressionQuality);
    }
}